$(function () {
    loadTeacherList();
});

function loadTeacherList() {
    $.ajax({
        url:"/api/teacher/list"
    }).done(function (data) {
        // console.log(data)
        let html = "";
        data.forEach((element,index) => {
            html += "<tr>"
            html += "<td>"+element.id+"</td>"
            html += "<td>"+element.teacher_id+"</td>"
            html += "<td>"+element.tname+"</td>"
            html += "<td>"+element.tage+"</td>"
            html += "<td><a href='#' onclick='showTeacherDlg("+element.id+")'>编辑</a>"+"</td>"
            html += "<td><a href='#' onclick='deleteTeacherDlg("+element.id+")'>删除</a>"+"</td>"
            html += "</tr>";
        })
        $("#teacherTb").html(html)
    });
}

let layerIndex;
function showTeacherDlg(id){
    let title="新增教师"
    if(id){
        //如果id存在，则为编辑
        title="编辑教师"
        $("#formId").css("display","block");//编辑教师，显示id
        //读取教师信息
        $.ajax({
            url:"/api/teacher/list/"+id,
            method:"GET",
        }).done(result=>{
            console.log(result)
            //遍历result对象并将值填充到 #stuForm表单
            $.each(result,function(key,vaule){
                //修改选择器，确保选择的是 #stuForm 内的字段
                var field=$('#teacForm [name="' + key + '"]');
                if(field.is(':radio')){
                    field.filter('[value="'+vaule+'"]').prop('checked',true);
                }
                else if(field.is(':checkbox')){
                    field.prop('checked',vaule === "yes");
                }
                else{
                    field.val(vaule);
                }
            });
        })
    }
    else{
        //否则为新增
        $("#teacForm")[0].reset();//清空#teacForm表单
        $("#formId").css("display","none");//新增教师，隐藏id
    }
    layerIndex=layer.open({
        type: 1,
        title: title,
        area: ['600px','auto'],
        content: $('#teacForm')
    });
}

layui.use(function (){
    layui.form.on('submit(teac-dlg)', function (data) {
        event.preventDefault();//阻止表单默认提交
        commitTeacDlg();
    })
});

function commitTeacDlg(){
    let formData = $("#teacForm").serialize(); //读取表单数据
    let id=$("#id").val();
    if(id!=null&&id!=""){
        //如果id不为空，则为修改教师
        //修改教师
        //验证表单是否合法(会自动验证教师号)
        $.ajax({
            url: "/api/teacher/update",
            method: "PUT",
            data: formData
        }).done(result=>{
            console.log(result);
            if(result.id){
                //读取并刷新教师列表
                loadTeacherList();
                //关闭弹出层
                console.log("update successfully");
                if(layerIndex){
                    layer.close(layerIndex);
                }
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed："+ textStatus + " - "+errorThrown);
            alert("An error occured,Please try again");
        });
    }
    else{
        //否则为新增教师
        //新增教师
        //验证表单是否合法(会自动验证教师号)
        $.ajax({
            url: "/api/teacher/add",
            method: "POST",
            data: formData
        }).done(result=>{
            console.log(result);
            if(result.id){
                //读取并刷新教师列表
                loadTeacherList();
                //关闭弹出层
                console.log("added successfully");
                if(layerIndex){
                    layer.close(layerIndex);
                }
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed："+ textStatus + " - "+errorThrown);
            alert("An error occured,Please try again");
        });
    }
    $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");//禁用按钮
}

//删除教师
function deleteTeacherDlg(id){
    layer.confirm('是否确定删除该教师？', {icon: 3}, function(){
        $.ajax({
            url:"/api/teacher/delete/"+id,
            method:"DELETE"
        }).done(result=>{
            console.log(result);
            //读取并刷新学生列表
            loadTeacherList();
        })
        layer.closeAll();//关闭所有弹出层
    }, function(){});
}